package com.homepage.web.rest;

import com.homepage.repository.CompanyLogoRepository;
import com.homepage.service.CompanyLogoService;
import com.homepage.service.dto.CompanyLogoDTO;
import com.homepage.util.HeaderUtil;
import com.homepage.util.ResponseUtil;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;


/**
 * REST controller for managing {@link com.homepage.domain.CompanyLogo}.
 */
@RestController
@RequestMapping("/company")
public class CompanyLogoResource {

    private final Logger log = LoggerFactory.getLogger(CompanyLogoResource.class);

    private static final String ENTITY_NAME = "companyLogo";

    @Value("${common.clientApp.name}")
    private String applicationName;

    private final CompanyLogoService companyLogoService;

    private final CompanyLogoRepository companyLogoRepository;

    public CompanyLogoResource(CompanyLogoService companyLogoService, CompanyLogoRepository companyLogoRepository) {
        this.companyLogoService = companyLogoService;
        this.companyLogoRepository = companyLogoRepository;
    }
    /**
     * {@code PUT  /company-logos} : Create a new companyLogo.
     *
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new companyLogoDTO, or with status {@code 400 (Bad Request)} if the companyLogo has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping(value = "/{companyName}/logo", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    @ResponseBody
    public ResponseEntity<ModelMap>  createCompanyLogo(@PathVariable String companyName,
                                                       @RequestPart MultipartFile picData) throws URISyntaxException, IOException {
        log.debug("REST request to save Company Logo" );
        InputStream is = picData.getInputStream();
        String contentType = picData.getContentType();
        String fileName = picData.getOriginalFilename();
        log.debug("store image : " );
        byte[] pictureData = new byte[(int) picData.getSize()];
        int length = is.read(pictureData);
        CompanyLogoDTO companyLogoDTO = new CompanyLogoDTO();
        companyLogoDTO.setLogoContentType(contentType);
        companyLogoDTO.setLogo(pictureData);
        companyLogoDTO.setCompanyId(companyName);
        companyLogoService.save(companyLogoDTO);

        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("code", HttpStatus.CREATED.value());
        return ResponseEntity
            .created(new URI("/api/"+companyName+"/logo" ))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, companyName + "-logo"))
            .body(modelMap);
    }

    @GetMapping("/{companyName}/logo")
    public ResponseEntity<byte[]> getPicturebyName(@PathVariable(value = "companyName")  String companyName){
        CompanyLogoDTO companyLogoDTO = companyLogoService.findByCompanyName(companyName);
        if(companyLogoDTO == null)
        {
            return new ResponseEntity(null,null, HttpStatus.NOT_FOUND);
        }
        HttpHeaders headers = new HttpHeaders();
        if(companyLogoDTO.getLogoContentType().equalsIgnoreCase(MediaType.IMAGE_JPEG_VALUE))
            headers.setContentType(MediaType.IMAGE_JPEG);
        if(companyLogoDTO.getLogoContentType().equalsIgnoreCase(MediaType.IMAGE_PNG_VALUE))
            headers.setContentType(MediaType.IMAGE_PNG);
        headers.setContentLength(companyLogoDTO.getLogo().length);

        return new ResponseEntity<byte[]>(companyLogoDTO.getLogo(), headers, HttpStatus.OK);
    }


    /**
     * {@code DELETE  /company-logos/:id} : delete the "id" companyLogo.
     *
     * @param id the id of the companyLogoDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/company-logos/{id}")
    public ResponseEntity<Void> deleteCompanyLogo(@PathVariable Long id) {
        log.debug("REST request to delete CompanyLogo : {}", id);
        companyLogoService.delete(id);
        return ResponseEntity
            .noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
